import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import util from '@/utils/utils'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

// 创建axios实例对象，添加全局配置
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 300000,//5分钟
    withCredentials: true
})

// 请求拦截
service.interceptors.request.use((req)=>{
    const headers = req.headers
    let token = util.getToken()
    // console.log(token);
    if(!token){
        token = "";
    }
    if (!headers.Authorization) headers.Authorization = token
    if('post'===req.method && 'multipart/form-data' === headers['Content-Type']){
        headers['Content-Type'] = 'multipart/form-data';
    }else{
        headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    return req
})

// 响应拦截
service.interceptors.response.use((res)=>{
    //console.log(res);
    if(res.config.responseType === "arraybuffer"){
        let base64Img = btoa(String.fromCharCode.apply(null, new Uint8Array(res.data)));
        // console.log('图片',base64Img);
        return Promise.resolve('data:image/jpeg;base64,' + base64Img);
    }
    const { code, msg } = res.data
    if (code === 200) {
        return res.data
    }else if (code === 504) {
        ElMessage.error('凭证过期或无效')
        setTimeout(()=>{
            router.push('/login')
        }, 1500);
    }  else if (code === 50001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(()=>{
            router.push('/login')
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
})

/**
 * 请求的核心函数
 * @param {*} options 请求配置
 * @returns {AxiosPromise}
 */
function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }else if (options.method.toLowerCase() === 'post'||options.method.toLowerCase() === 'put') {
        //上传文件 multipart/form-data
        //普通表单 application/x-www-form-urlencoded
        options.headers = {
            'Content-Type':'multipart/form-data'
        }
        options.data = options.data
    }
    return service(options)
}

['get','post','put','delete','patch'].forEach((item)=>{
    request[item] = (url,data,options)=>{
        return request({
            url,
            data,
            methods:item,
            ...options
        })
    }
})

export default request